package com.tanhua.sso.service;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.tanhua.sso.config.AliyunSMSConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class SmsService {

    @Autowired
    private AliyunSMSConfig aliyunSMSConfig;

    /**
     * 发送短信验证码
     *
     * @param mobile
     * @return
     */
    public String sendSms(String mobile) {
        //随机生成6位数字验证码
        String code = RandomUtil.randomNumbers(6);
        try {
            Config config = new Config()
                    .setAccessKeyId(this.aliyunSMSConfig.getAccessKeyId())
                    .setAccessKeySecret(this.aliyunSMSConfig.getAccessKeySecret())
                    .setEndpoint(this.aliyunSMSConfig.getDomain());

            Client client = new Client(config);
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(mobile)//目标手机号
                    .setSignName(this.aliyunSMSConfig.getSignName()) //签名名称
                    .setTemplateCode(this.aliyunSMSConfig.getTemplateCode()) //短信模板code
                    .setTemplateParam("{\"code\":\"" + code + "\"}"); //模板中变量替换
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            SendSmsResponseBody body = sendSmsResponse.getBody();
            if (StrUtil.equals("OK", body.getCode())) {
                return code;
            }
        } catch (Exception e) {
            log.error("发送短信验证码失败！" + mobile, e);
        }
        return null;
    }
}
